﻿using System;
using Nb.Common.Configurations;

namespace Nb.Common.Aop
{
    public class NbPerformanceTraceService : INbPerformanceTraceService
    {
        public bool ShouldIntercept(Type serviceType)
        {
            string nameSpace = serviceType.Namespace;
            if (nameSpace == null)
            {
                return false;
            }

            if (!nameSpace.StartsWith("Nb.", StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            if (!serviceType.IsInterface)
            {
                //var siteService = CoreServiceProvider.LocateService<ISiteService>(); //ok
                //var siteService = CoreServiceProvider.LocateService<SiteService>(); //导致aop失败！
                return false;
            }

            if (nameSpace.StartsWith("Nb.BaseLib.", StringComparison.OrdinalIgnoreCase)
                || (nameSpace.StartsWith("Nb.Web.Areas.", StringComparison.OrdinalIgnoreCase) && nameSpace.NbContains("Lib"))
                || nameSpace.StartsWith("Nb.Web.Common.", StringComparison.OrdinalIgnoreCase)
                //|| nameSpace.StartsWith("Nb.Common.", StringComparison.OrdinalIgnoreCase)
                )
            {
                return true;
            }

            return false;
        }

        private static int? importantSpan = null;
        public int InterceptionSlowSpan()
        {
            if (!importantSpan.HasValue)
            {
                const string EnableInterceptKey = "EnableIntercept";
                importantSpan = ConfigHelper.GetAppSettingValueOfInt(EnableInterceptKey, 100);
            }

            return importantSpan.Value;
        }

        private static bool? performanceTraceEnabled;
        public bool PerformanceTraceEnabled()
        {
            if (!performanceTraceEnabled.HasValue)
            {
                const string PerformanceTraceEnabledKey = "PerformanceTraceEnabled";
                performanceTraceEnabled = ConfigHelper.GetAppSettingValueOfBoolean(PerformanceTraceEnabledKey);
            }

            return performanceTraceEnabled.Value;
        }
    }
}
